<?php

namespace App\Services\RegisterNewUser;

use App\Models\User;
use App\Services\UserInviteInfo\UserInviteInfo;

class RegisterNewUser
{
	protected $name;
	
	protected $phone;
	
	protected $password;
	
	/**
	 * @var User
	 */
	protected $inviter = null;
	
	public function __construct( $phone,  $inviteCode = null)
	{
		$this->phone = $phone;
		$this->setInviter($inviteCode);
	}
	
	protected function setInviter($inviteCode)
	{
		if (! $inviteCode) return;
		$this->inviter = app(UserInviteInfo::class)->userFromInviteCode($inviteCode);
	}
	
	protected function registerByInviter()
	{
		return $this->inviter->children()->create([
			'grade' => 'noraml',
			'phone' => $this->phone,
			'password' => bcrypt(000000)
		]);
	}
	
	protected function registerBySelf()
	{
		return User::create([
			'grade' => 'noraml',
			'phone' => $this->phone,
			'password' => bcrypt(000000),
			'times'=>1,
		]);
	}
	
	public function register()
	{
		
		if ($this->inviter) {
			return $this->registerByInviter();
		}
		
		return $this->registerBySelf();
	}
}
